#pragma once

#include<iostream>
#include<string>
#include<vector>
#include<queue>
#include"task.hpp"
#include"Lock.hpp"
using namespace std;


static const int n=5;
template<class T>
class ThreadPool
{
public:
    ThreadPool(int num=n):_num(num),_threads(num)
    {
        pthread_mutex_init(&_mt,nullptr);
        pthread_cond_init(&_cd,nullptr);
    }
    void Lockqueue()
    {
        pthread_mutex_lock(&_mt);
    }
    void Unlockqueue()
    {
        pthread_mutex_unlock(&_mt);

    }
    void Threadwait()
    {
        pthread_cond_wait(&_cd,&_mt);
    }

    void Threadwakeup()
    {
        pthread_cond_signal(&_cd);
    }

    bool isEmpty()
    {
        return _tasks.empty();
    }

    T popTask()
    {
        T t=_tasks.front();
        _tasks.pop();
        return t;
    }

    //静态不能访问类内私有成员，所以传入this指针
    static void * Thread_Ring_C(void * args)
    {
        pthread_detach(pthread_self());

        ThreadPool<T>* tp=static_cast<ThreadPool<T>*>(args);

        while(true)
        {
            tp->Lockqueue();  //加锁

            while(tp->isEmpty())  //判断环形队列里是否为空
            {
                tp->Threadwait();    //弱满足条件就等待
            }

            T t = tp -> popTask();   //记录任务

            tp->Unlockqueue();  //解锁


            t();   //计算任务

            cout<<"线程已经处理完成任务："<<t.Printres()<<enld;
        }
    }

    void init()
    {
        for(int i=0;i<_num;i++)
        {
            _threads.push_back(Thread(i,Thread_Ring_C,this));
        }

    }












    void start()
    {
        for(auto &t:_threads)
        {
        //     pthread_create(&_threads[i],nullptr,Thread_Ring_C,this);
            t.Running();
        }
    }














    void pushTask(const T &t)
    {
        Lockqueue();
        _tasks.push(t);
        Threadwakeup();
        Unlockqueue();
    }
    










    ~ThreadPool()
    {
        for(auto &t:_threads)
        {
            t.join();
        }



        pthread_mutex_destroy(&_mt);
        pthread_mutex_destroy(&_cd);
    }








private:
    vector<pthread_t> _threads;
    int _num;

    queue<T> _tasks;

    pthread_mutex_t _mt;
    pthread_cond_t _cd;

};